// 用户模块-mysql服务处理

// 引入数据库模块
const db = require('../config/mysql.js')
const utils = require("../common/utils")

// 修改用户信息
const updateUserInfo = (data) => {
  return new Promise((resolve, reject) => {
    let { id, user_name, gender, birthday, phone, sign, avatar } = data
    const obj = { user_name, gender, birthday, phone, sign, avatar }
    let str = ''
    // 过滤掉空数据,sql语句处理
   for (let key in obj) {
     if (obj[key].trim() != '') {
       if (key == 'birthday') {
         str += `${key} = "${obj[key].trim()}",`
       } else {
         str += `${key} = ${obj[key].trim()},`
       }
     }
   }
   str = utils.deleteStrByWay(str, ',')
   let sql = `update user set ${str} where id = ${id}`
   db.query(sql, (err, result) => {
     if (err) return reject(err)
     if (result.affectedRows == 1) return resolve("修改成功")
     return reject("修改失败")
   })
  })
}

// 修改好友备注
const setMark = (uid, fid, nick_name) => {
  return new Promise((resolve, reject) => {
    let sql = `update friend set nick_name = "${nick_name}" where user_id = "${uid}" and friend_id = "${fid}" and friend_status = 2`
    db.query(sql, (err, result) => {
      if (err) return reject(result)
      if (result.affectedRows == 1) {
        return resolve("修改备注成功")
      } else {
        return reject('修改备注失败')
      }
    })
  })
}

module.exports = {
  updateUserInfo,
  setMark
}